package com.auto.learning.fragment;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.activity.BookCommentFragmentActivity;
import com.auto.learning.activity.PlayActivity;
import com.auto.learning.activity.PublicCommentActivity;
import com.auto.learning.adapter.CommentFragmentAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ImageCommentBean;
import com.auto.learning.bean.ImageItem;
import com.auto.learning.bean.ImagesBean;
import com.auto.learning.bean.ReadModeBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.ProgressEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.pay.UserBuyUtils;
import com.auto.learning.service.DownLoadManager;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.ImagePopWindowUtils;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.RoundImageView;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * 评论 fragment
 * @author wangjianjun
 */
public class CommentFragment extends Fragment implements Callback {
	
	private final static int GET_COMMENT_LIST_SUCCESS = 2;
	private final static int GET_COMMENT_LIST_FAIL = 3;
	private final static int CLICK_FAVOUR = 4;
	private final static int CLICK_FAVOUR_SUCCESS = 5;
	private final static int CLICK_FAVOUR_DEL_SUCCESS = 6;
	private final static int SEND_COMMENT_SUCCESS = 7;
	private final static int DELETE_COMMENT_SUCCESS = 8;
	private final static int DELETE_COMMENT= 9;
	private final static int CHECK_IMAGE_DELTAIL = 10;
	private final static int CLICK_COMENT = 11;
	private final static int COMMENT_SHARE = 12;
	private final static int COMMENT_REPORT = 13;
	private final static int COMMENT_REPORT_SUCCESS = 14;
	
	private RelativeLayout comment_main_view;
	private TextView tv_commnet;
	private PullToRefreshListView listview_comment;
	private CommentFragmentAdapter adapter;
	private RelativeLayout rel_bottom;
	private ArrayList<ImageCommentBean> list = new ArrayList<ImageCommentBean>();
	private int pageIndex = 0;
	
	private View lvProductFooter,lvFooter_no_data;
	private TextView lvProductFooterMore;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;
	private Map<String , Object> mMap ;
	
	int bookId;
	private LinearLayout linear_download;
	private ReadModeBean readModeBean = new ReadModeBean();
	private TextView tv_xcy,tv_download,tv_bookname,tv_slogan,tv_listen_number,tv_shoucang_number,tv_pinglun_number;
	private DisplayImageOptions options;
	private View headView;
	private ImageView f_image_play,f_image_guoqi,image_download;
	private RoundImageView f_image_face;
	
	private TextView tv_comment_list,tv_read_all,tv_comment_no_data;
	private View tv_comment_line,tv_read_all_line,tv_anchor_all_line;
	private RelativeLayout rel_left, rel_mid;
	
	
	private final static int GETCACHEDATA_SUCCESS = 15;
	private final static int DOWNLOAD_PROGRESS = 16;
	private LinearLayout linear_tab;
	private Handle handle = new Handle(getActivity()){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult _result = (ResponeResult)msg.obj;
				readModeBean = new Gson().fromJson(_result.getData(), new TypeToken<ReadModeBean>(){}.getType());
				showView();
				Cache.cacheReadMode2Local(readModeBean);
				break;
			case GETCACHEDATA_SUCCESS:
				if (readModeBean.getBookId() > 0) {
					showView();
				}
				getData();
				break;
			case DOWNLOAD_PROGRESS:
				ProgressEvent event = (ProgressEvent)msg.obj;
				if (event.getBookId() == bookId) {
					if (event.getCurrentRatio() == 100) {
						image_download.setBackgroundResource(R.drawable.xiazaiok);
						tv_download.setText("已下载");
					}else {
						linear_download.setEnabled(false);
						tv_download.setText(event.getCurrentRatio()+"%");
						image_download.setBackgroundResource(R.anim.download_stute);
						AnimationDrawable _animaition = (AnimationDrawable)image_download.getBackground();
						_animaition.setOneShot(false);   
						_animaition.start();
					}
				}
				break;
			case GET_COMMENT_LIST_SUCCESS:
				String bottom = "";
				ResponeResult result =(ResponeResult) msg.obj;
				ArrayList<ImageCommentBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<ImageCommentBean>>() {}.getType());
				if (pageIndex == 0) {
					list.clear();
					list.addAll(resultList);
				} else {
					list.addAll(resultList);
				}
				if (list.size() > 0) {
					tv_comment_no_data.setVisibility(View.GONE);
					lvProductFooter.setVisibility(View.VISIBLE);
				}else {
					tv_comment_no_data.setVisibility(View.VISIBLE);
					lvProductFooter.setVisibility(View.GONE);
				}
				if (resultList.size() >= 10) {
					pageIndex ++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				}else {
					bottom = getResources().getString(R.string.text_no_data_comment);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}
				
				if (listview_comment != null) {
					listview_comment.onRefreshComplete();
					listview_comment.setTag(0);
				}
				if (list != null && list.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case GET_COMMENT_LIST_FAIL:
				try {
					CommonMethod.makeNotice(getActivity(), msg.obj.toString());
					if (listview_comment != null) {
						listview_comment.onRefreshComplete();
						listview_comment.setTag(0);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case CLICK_FAVOUR:
				Map<String, Object> map = (Map<String, Object>) msg.obj;
				supportComment(map);
				break;
			case CLICK_FAVOUR_SUCCESS:
				if (mMap != null) {
					int commentId = (int) mMap.get("commentId");
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).getId() == commentId) {
							list.get(i).setFavourNum(list.get(i).getFavourNum() + 1);
							list.get(i).setIsFavour(2);
							if (adapter != null) {
								adapter.notifyDataSetChanged();
							}
							break;
						}
					}
				}
				break;
			case CLICK_FAVOUR_DEL_SUCCESS:
				if (mMap != null) {
					int commentId = (int) mMap.get("commentId");
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).getId() == commentId) {
							list.get(i).setFavourNum(list.get(i).getFavourNum() - 1);
							list.get(i).setIsFavour(1);
							if (adapter != null) {
								adapter.notifyDataSetChanged();
							}
							break;
						}
					}
				}
				break;
			case DELETE_COMMENT_SUCCESS:
				ResponeResult delete_result = (ResponeResult)msg.obj;
				int commentId = delete_result.getCode();
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).getId() == commentId) {
						list.remove(i);
						break;
					}
				}
				if (list.size() > 0) {
					tv_comment_no_data.setVisibility(View.GONE);
					lvProductFooter.setVisibility(View.VISIBLE);
				}else {
					tv_comment_no_data.setVisibility(View.VISIBLE);
					lvProductFooter.setVisibility(View.GONE);
				}
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				break;
			case DELETE_COMMENT:
				final int comId = msg.arg2;
				final int bId = msg.arg1;
				CommonAlertDialog alertDialog = new CommonAlertDialog(getActivity());
				alertDialog.setTextMessage("确定删除这条评论吗？");
				alertDialog.setShowTitle(true);
				String[] a = {"确定","取消"};
				alertDialog.setBtns(new DialogListener() {

					@Override
					public void okButtonClick(Dialog dialog) {
						deleteComment(comId,bId);
						dialog.dismiss();
					}

					@Override
					public void cancelButtonClick(Dialog dialog) {
						dialog.dismiss();
					}

					@Override
					public void otherButtonClick(Dialog dialog) {
						dialog.dismiss();
					}}, a);
				alertDialog.show();
				break;
			case CHECK_IMAGE_DELTAIL:
				ArrayList<ImagesBean> imagesBeans = (ArrayList<ImagesBean>) msg.obj;
				ArrayList<ImageItem> tempImageItems = new ArrayList<ImageItem>();
				for (ImagesBean imagesBean : imagesBeans) {
					ImageItem imageItem = new ImageItem();
					imageItem.sourcePath = imagesBean.getImgUrl();
					tempImageItems.add(imageItem);
				}
				DisplayMetrics dm = new DisplayMetrics();
				getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
				ImagePopWindowUtils utils=new ImagePopWindowUtils(tempImageItems,msg.arg1, getActivity(), dm);
				utils.getPopupWindow().showAtLocation(comment_main_view, Gravity.CENTER, 0, 0);
				break;
			case CLICK_COMENT:
				Map<String, Object> bookInfo = ((PlayActivity)getActivity()).getCommentBookInfo();
				Intent mIntent = new Intent(getActivity(), BookCommentFragmentActivity.class);
				mIntent.putExtra("bookId", bookId);
				mIntent.putExtra("commentId", msg.arg1);
				mIntent.putExtra("bookName", bookInfo.get("bookName") + "");
				mIntent.putExtra("imgFace", bookInfo.get("imgFace") + "");
				mIntent.putExtra("imgFacePlay", bookInfo.get("imgFacePlay") + "");
				mIntent.putExtra("imageBean", list.get(msg.arg2));
				startActivity(mIntent);
				break;
			case COMMENT_SHARE:
				Map<String, Object> temp_Map = ((PlayActivity)getActivity()).getCommentBookInfo();
				if (temp_Map != null) {
					String bookName = temp_Map.get("bookName") + "";
					String imgFacePlay = temp_Map.get("imgFacePlay") + "";
					
					String url = HttpCommonInfo.MURL +"book-comment-share?bookId=" + bookId +"&id="+ msg.arg1;
					String title = list.get(msg.arg2).getName() + "的读后感";
					String content = bookName;
					new ShareView(getActivity(), CommentFragment.this).setTitle(title).setUrl(url).setContent(content).setImageUrl(imgFacePlay).setType(4).setId(bookId+"").show(comment_main_view);
				}
				break;
			case COMMENT_REPORT_SUCCESS:
				CommonMethod.makeNotice(getActivity(), "感谢您热心举报，我们会尽快处理");
				break;
			case COMMENT_REPORT:
				final int cuId = msg.arg1;
				String[] aA = {"举报","取消"};
				CommonMethod.showDialog(getActivity(), aA, "确定举报这条书评吗?", new DialogListener() {
					
					@Override
					public void otherButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
					
					@Override
					public void okButtonClick(Dialog dialog) {
						dialog.dismiss();
						reportComment(cuId);
					}
					
					@Override
					public void cancelButtonClick(Dialog dialog) {
						dialog.dismiss();
					}
				});
				break;
			
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.comment_fragment, null);
		initView(view);
		registerEvent();
		initImageLoader();
		initData();
		return view;
	}
	
	private void initData(){
		readModeBean = ((PlayActivity)getActivity()).getReadModeFromReadFragment();
		if (readModeBean != null && readModeBean.getBookId() > 0 && !TextUtils.isEmpty(readModeBean.getAuthor())) {
			showView();
		}else {
			getPageCache();
		}
	}
	
	private void showView(){
		if (readModeBean != null && readModeBean.getBookId() > 0) {
			ImageLoader.getInstance().displayImage(readModeBean.getFaceImgPlay(), f_image_face,options);
			ImageLoader.getInstance().displayImage(readModeBean.getNationImg(), f_image_guoqi);
			tv_xcy.setText(readModeBean.getSlogan()+"");
			tv_bookname.setText(readModeBean.getBookName()+"");
			tv_slogan.setText(readModeBean.getAuthor()+"");
			tv_listen_number.setText(readModeBean.getListenNum()+"");
			tv_shoucang_number.setText(readModeBean.getFavorNum()+"");
			tv_pinglun_number.setText(readModeBean.getCommentNum()+"");
			tv_need_price.setText(readModeBean.getPriceTag()+"");
			if (readModeBean.getFree() == 1) {
				image_price.setVisibility(View.VISIBLE);
				tv_need_price.setVisibility(View.VISIBLE);
			} else {
				image_price.setVisibility(View.GONE);
				tv_need_price.setVisibility(View.GONE);
			}
			if (TemporaryVariable.downLoadedList.contains(bookId)) {
				image_download.setBackgroundResource(R.drawable.xiazaiok);
				tv_download.setText("已下载");
			}else {
				image_download.setBackgroundResource(R.drawable.xiazai2);
				tv_download.setText("下载");
			}
			updateUi();
		}
	}
	
	public void updateUi(){
		int playingBookId[] = MusicPlayManager.getInstance(getActivity()).isPlayingBookId();
		if (playingBookId[0] != 0 && playingBookId[0] == readModeBean.getBookId()) {
			if (playingBookId[2] == 0) 
				f_image_play.setImageResource(R.drawable.playing);
			else 
				f_image_play.setImageResource(R.drawable.play);
		} else {
			f_image_play.setImageResource(R.drawable.play);
		}
	}
	
	
	
	public ReadModeBean getReadModeBean() {
		return readModeBean;
	}

	public void setReadModeBean(ReadModeBean readModeBean) {
		this.readModeBean = readModeBean;
	}

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	
	boolean isPlaying = false;
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		if (MusicPlayManager.getInstance(getActivity()).getPlayList() != null) {
			int ids[] = MusicPlayManager.getInstance(getActivity()).isPlayingBookId();
			if (ids[0] == bookId) {
				this.isPlaying = isPlaying;
				MusicPlayManager.getInstance(getActivity()).setPlaying(isPlaying);
				if (ids[0] != 0) {
					setBookId(ids[0]);
				}
				updateUi();
			}
		}
	}
	
	@Subscribe
	public void onEventProgress(ProgressEvent event){
		handle.obtainMessage(DOWNLOAD_PROGRESS, event).sendToTarget();
	}
	
	private void getPageCache(){
		Pool.getPool().execute(new Runnable() {
			@Override
			public void run() {
				try {
					BookBean bean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(bookId);
					if (bean != null) {
						readModeBean.setBookId(bookId);
						readModeBean.setBookName(bean.getBookName());
						readModeBean.setFaceImg(bean.getFaceImg());
						readModeBean.setFaceImgPlay(bean.getFaceImgPlay());
						readModeBean.setNationImg(bean.getNationImg());
						readModeBean.setAbout(bean.getAbout());
						readModeBean.setGoldWord(bean.getGoldWord());
						readModeBean.setAuthor(bean.getAuthor());
						readModeBean.setCommentNum(bean.getCommentNum());
						readModeBean.setFavorNum(bean.getFavorNum());
						readModeBean.setListenNum(bean.getListenNum());
						readModeBean.setProSize(bean.getProSize());
						readModeBean.setEnSize(bean.getEnSize());
						readModeBean.setDoubiSize(bean.getDoubiSize());
						readModeBean.setIsFavor(bean.getIsFavor());
						readModeBean.setSlogan(bean.getSlogan());
						readModeBean.setIsNew(bean.getIsNew());
						readModeBean.setCanRead(bean.getCanRead());
						
						readModeBean.setFree(bean.getFree());
						readModeBean.setPriceTag(bean.getPriceTag());
						readModeBean.setNeedBuy(bean.getNeedBuy());
						List<SelectionVo> list_vo =	StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryBuilder().where().eq("bookId", bookId).query();
						if (list_vo != null) {
							readModeBean.setSectionList(list_vo);
						}
					}
					handle.sendEmptyMessage(GETCACHEDATA_SUCCESS);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private void getData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.READ_MODE, params, handle, HttpRequestHelper.GETDATA_SUCCESS);
	}
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.default_512)
		.showImageForEmptyUri(R.drawable.default_512).showImageOnFail(R.drawable.default_512).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build();
	}
	
	
	/**
	 * 发布完评论后
	 * @param imageCommentBean
	 */
	@Subscribe
	public void refreshCommentList(ImageCommentBean imageCommentBean){
		if (imageCommentBean != null) {
			int k = -1;
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getId() == imageCommentBean.getId()) {
					k = i;
					break;
				}
			}
			if (k > -1) {
				list.get(k).setReplyNum(imageCommentBean.getReplyNum());
			} else {
				list.add(0,imageCommentBean);
			}
			if (list.size() > 0) {
				tv_comment_no_data.setVisibility(View.GONE);
				lvProductFooter.setVisibility(View.VISIBLE);
			}else {
				tv_comment_no_data.setVisibility(View.VISIBLE);
				lvProductFooter.setVisibility(View.GONE);
			}
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	/**
	 * 发布完评论后
	 * @param imageCommentBean
	 */
	@Subscribe
	public void refreshCommentList(Integer commentId){
		if (commentId > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getId() == commentId) {
					list.get(i).setReplyNum(list.get(i).getReplyNum() - 1);
					break;
				}
			}
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
	}
	private ImageView image_price;
	private TextView tv_need_price;
	
	private void initView(View view){
		lvFooter_no_data = LayoutInflater.from(getActivity()).inflate(R.layout.comment_data_empty, null);
		tv_comment_no_data = (TextView) lvFooter_no_data.findViewById(R.id.tv_comment_no_data);
		tv_comment_no_data.setVisibility(View.GONE);
		headView = LayoutInflater.from(getActivity()).inflate(R.layout.read_fragment_top, null);
		image_price = (ImageView) headView.findViewById(R.id.image_price);
		tv_need_price = (TextView) headView.findViewById(R.id.tv_need_price);
		image_price.setVisibility(View.GONE);
		tv_need_price.setVisibility(View.GONE);
		linear_download = (LinearLayout) headView.findViewById(R.id.linear_download);
		f_image_face = (RoundImageView) headView.findViewById(R.id.f_image_face);
		f_image_play = (ImageView) headView.findViewById(R.id.f_image_play);
		f_image_guoqi = (ImageView) headView.findViewById(R.id.f_image_guoqi);
		tv_bookname = (TextView) headView.findViewById(R.id.tv_bookname);
		tv_slogan = (TextView) headView.findViewById(R.id.tv_slogan);
		tv_listen_number = (TextView) headView.findViewById(R.id.tv_listen_number);
		tv_shoucang_number = (TextView) headView.findViewById(R.id.tv_shoucang_number);
		tv_pinglun_number = (TextView) headView.findViewById(R.id.tv_pinglun_number);
		tv_xcy = (TextView) headView.findViewById(R.id.tv_xcy);
		image_download = (ImageView) headView.findViewById(R.id.image_download);
		tv_download = (TextView) headView.findViewById(R.id.tv_download);
		tv_comment_list = (TextView) headView.findViewById(R.id.tv_comment_list);
		tv_comment_line =  headView.findViewById(R.id.tv_comment_line);
		tv_read_all_line =  headView.findViewById(R.id.tv_read_all_line);
		tv_anchor_all_line =  headView.findViewById(R.id.tv_anchor_all_line);
		tv_read_all = (TextView) headView.findViewById(R.id.tv_read_all);
		rel_left = (RelativeLayout) headView.findViewById(R.id.rel_left);
		rel_mid = (RelativeLayout) headView.findViewById(R.id.rel_mid);
		tv_comment_list.setTextColor(getResources().getColor(R.color.main_green_color));
		tv_read_all_line.setVisibility(View.INVISIBLE);
		tv_anchor_all_line.setVisibility(View.INVISIBLE);
		tv_read_all.setTextColor(getResources().getColor(R.color.white));
		tv_comment_line.setVisibility(View.VISIBLE);
		linear_tab=(LinearLayout) headView.findViewById(R.id.linear_tab);
		if(((PlayActivity) getActivity()).getCanRead()==1){
			rel_left.setVisibility(View.GONE);
			linear_tab.setVisibility(View.GONE);
		}
		rel_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((PlayActivity)getActivity()).checkToRead();
			}
		});
		rel_mid.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				((PlayActivity)getActivity()).checkToAnchor();
			}
		});
		
		linear_download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (readModeBean != null && !TemporaryVariable.downLoadedList.contains(readModeBean.getBookId()) && CommonMethod.checkUserLogin(getActivity())) {
					int downLoadSize = readModeBean.getDoubiSize() + readModeBean.getProSize() +readModeBean.getEnSize();
					if (downLoadSize > 0) {
						if (!TemporaryVariable.downLoadedList.contains(readModeBean.getBookId())) {
							StatService.onEvent(getActivity(), "LogEventTypeDownloadButtonClic", "下载按钮");
							DownLoadManager.getInstance(getActivity()).setContext(getActivity()).prepareBefore(bookId,downLoadSize);
						}
					}
				}
			}
		});
		f_image_play.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				MusicPlayManager manager = MusicPlayManager.getInstance(getActivity());
				if (manager.getPlayList() != null && manager.getPlayList().size() > 0) {
					int ids[] = manager.isPlayingBookId();
					if (ids[0] == bookId) {
						MusicPlayManager.getInstance(getActivity()).pause();
					} else {
						if(((PlayActivity)getActivity()).getNeedBuy() == 2&&!TemporaryVariable.downLoadedList.contains(bookId)){
							new UserBuyUtils(((Activity)getActivity()), bookId, readModeBean.getPriceTag(),readModeBean.getBookName()).buy();
							return;
						}
						BookBean bookBean = new BookBean();
						bookBean.setBookId(bookId);
						bookBean.setSectionList(readModeBean != null ? readModeBean.getSectionList() : null);
						bookBean.setBookName(readModeBean.getBookName());
						bookBean.setSlogan(readModeBean.getSlogan());
						bookBean.setFaceImg(readModeBean.getFaceImg());
						bookBean.setFaceImgPlay(readModeBean.getFaceImgPlay());
						((PlayActivity)getActivity()).getLocalBook(bookBean);
					}
				}else {
					if(((PlayActivity)getActivity()).getNeedBuy() == 2&&!TemporaryVariable.downLoadedList.contains(bookId)){
						new UserBuyUtils(((Activity)getActivity()), bookId, readModeBean.getPriceTag(),readModeBean.getBookName()).buy();
						return;
					}
					BookBean bookBean = new BookBean();
					bookBean.setBookId(bookId);
					bookBean.setSectionList(readModeBean != null ? readModeBean.getSectionList() : null);
					bookBean.setBookName(readModeBean.getBookName());
					bookBean.setSlogan(readModeBean.getSlogan());
					bookBean.setFaceImg(readModeBean.getFaceImg());
					bookBean.setFaceImgPlay(readModeBean.getFaceImgPlay());
					((PlayActivity)getActivity()).getLocalBook(bookBean);
				}
			}
		});
		
		
		
		comment_main_view = (RelativeLayout) view.findViewById(R.id.comment_main_view);
		comment_main_view.getBackground().setAlpha(200);
		tv_commnet = (TextView) view.findViewById(R.id.tv_comment);
		rel_bottom = (RelativeLayout) view.findViewById(R.id.rel_bottom);
		
		lvProductFooter = getActivity().getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);
		lvProductFooter.getBackground().setAlpha(0);
		
		listview_comment = (PullToRefreshListView) view.findViewById(R.id.listview_comment);
		listview_comment.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new CommentFragmentAdapter(getActivity(), list, handle);
		listview_comment.setAdapter(adapter);
		listview_comment.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				getPageCache();
				pageIndex = 0;
				getCommentList();
			}
		});
		listview_comment.setTag("0");
		listview_comment.addHeaderView(headView);
		listview_comment.addFooterView(lvProductFooter);
		listview_comment.addFooterView(lvFooter_no_data);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getCommentList();
			}
		});
		listview_comment.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listview_comment.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_no_data_comment))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int lvDataState = Integer.parseInt((listview_comment.getTag().toString()));
				if (scrollEnd && lvDataState == 0) {
					listview_comment.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = listview_comment.getCount() - 2;  // 减去ListView的头和尾的
					
					getCommentList();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				listview_comment.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
		bookId =((PlayActivity) getActivity()).getBookId();
		
		
		tv_commnet.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (CommonMethod.checkUserLogin(getActivity(),getResources().getString(R.string.text_no_login_comment))) {
					Intent intent = new Intent(getActivity(), PublicCommentActivity.class);
					intent.putExtra("bookId", bookId);
					startActivityForResult(intent,666);
				}
			}
		});
		listview_comment.clickRefresh();
	}
	
	
	public void getCommentList(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.BOOK_REVIEW_LIST, params, handle, GET_COMMENT_LIST_SUCCESS, GET_COMMENT_LIST_FAIL);
	}
	
	public void sendComment(Map<String, Object> map,String comment){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.COMMENTID, String.valueOf(map.get(HttpRequestHelper.COMMENTID))));
		params.add(new BasicNameValuePair("replyUser", String.valueOf(map.get("replyUser"))));
		params.add(new BasicNameValuePair("reply", comment));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.COMMENT_REPLY_ADD, params, handle, SEND_COMMENT_SUCCESS, GET_COMMENT_LIST_FAIL);
	}
	
	public void supportComment(Map<String, Object> map){
		mMap = map;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(map.get(HttpRequestHelper.BOOKID))));
		params.add(new BasicNameValuePair(HttpRequestHelper.COMMENTID, String.valueOf(map.get(HttpRequestHelper.COMMENTID))));
		int isFavour = (int)map.get("isFavour");
		if (isFavour == 2) {
			HttpRequestHelper.executeHttpDataNoData(getActivity(), HttpRequestHelper.COMMENT_FAVOUR_DEL, params, handle, CLICK_FAVOUR_DEL_SUCCESS, GET_COMMENT_LIST_FAIL);
		}else {
			HttpRequestHelper.executeHttpDataNoData(getActivity(), HttpRequestHelper.COMMENT_FAVOUR, params, handle, CLICK_FAVOUR_SUCCESS, GET_COMMENT_LIST_FAIL);
		}
	}
	
	private void reportComment(int commendId){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.COMMENTID, String.valueOf(commendId)));
		HttpRequestHelper.executeHttpDataNoData(getActivity(), HttpRequestHelper.COMMENT_WARN, params, handle, COMMENT_REPORT_SUCCESS, GET_COMMENT_LIST_FAIL);
	}
	
	/**
	 * 删除评论
	 * @param commendId
	 * @param bookId
	 */
	private void deleteComment(final int commendId, final int bookId){
		//请求数据
		Pool.getPool().execute(new Runnable() {
			@Override
			public void run() {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
				params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, bookId+""));
				params.add(new BasicNameValuePair(HttpRequestHelper.COMMENTID, String.valueOf(commendId)));
				ResponeResult responeResult = new ResponeResult();
				try {
					HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.BOOK_COMMENT_DELETE, params, getActivity());
					String _result = HttpHelper.entity2String(entity);
					JSONObject jsonResult = new JSONObject(_result);
					JSONObject result = jsonResult.getJSONObject(HttpCommonInfo.RESULT);
					int code = result.getInt(HttpCommonInfo.RESULT_CODE);
					String msg = result.getString(HttpCommonInfo.RESULT_MSG);
					responeResult.setCode(code);
					responeResult.setMsg(msg);
					if (code == 0) {
						responeResult.setCode(commendId);
						handle.obtainMessage(DELETE_COMMENT_SUCCESS, responeResult).sendToTarget();
					} else {
						handle.obtainMessage(GET_COMMENT_LIST_FAIL, responeResult).sendToTarget();
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					responeResult = null;
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					responeResult = null;
				} catch (IOException e) {
					e.printStackTrace();
					responeResult = null;
				} catch (JSONException e) {
					e.printStackTrace();
					responeResult = null;
				} finally {
					if (responeResult == null ) {
						handle.obtainMessage(GET_COMMENT_LIST_FAIL, getResources().getString(R.string.connect_err_io)).sendToTarget();
					}
				}
			}
		});
	}
	
	
	public void registerEvent(){
		EventBus.getEventBus("refresh_comment_list_delete" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("refresh_comment_list" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("downloadProgress",ThreadEnforcer.MAIN).register(this);
	}
	
	public void unRegisterEvent(){
		EventBus.getEventBus("refresh_comment_list_delete" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("refresh_comment_list" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("downloadProgress",ThreadEnforcer.MAIN).unregister(this);
	}
	
	@Override
	public void onDestroy() {
		unRegisterEvent();
		super.onDestroy();
	}
	
	/**
	 * scroll Vertical
	 * @param y 垂直滑动的距离
	 */
	public void scrollVertical(final ListView listView, Activity activity, final int y) {
		if (listView == null) return;
		activity.runOnUiThread(new Runnable() { // 执行自动化测试的时候模拟滑动需要进入UI线程操作
			@Override
			public void run() {
				invokeMethod(listView, "trackMotionScroll", new Object[] { -y, -y }, new Class[] { int.class, int.class });
			}
		});
	}
	
	/**
	 * 遍历当前类以及父类去查找方法，例子，写的比较简单
	 * @param object
	 * @param methodName
	 * @param params
	 * @param paramTypes
	 * @return
	 */
	public Object invokeMethod(Object object, String methodName, Object[] params, Class[] paramTypes) {
		Object returnObj = null;
		if (object == null) {
			return null;
		}
		Class cls = object.getClass();
		Method method = null;
		for (; cls != Object.class; cls = cls.getSuperclass()) { // 因为取的是父类的默认修饰符的方法，所以需要循环找到该方法
			try {
				method = cls.getDeclaredMethod(methodName, paramTypes);
				break;
			} catch (NoSuchMethodException e) {
			} catch (SecurityException e) {
			}
		}
		if (method != null) {
			method.setAccessible(true);
			try {
				returnObj = method.invoke(object, params);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return returnObj;
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(getActivity(), msg);
		return false;
	}
	
}
